package com.foreveross.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.foreveross.common.Constants;
import com.foreveross.dao.MessageDAO;
import com.foreveross.dao.MessageHouseDAO;
import com.foreveross.vo.HrHouses;
import com.foreveross.vo.Message;
import com.foreveross.vo.MessageHouse;

@Service("messageHouseService")
@Transactional
public class MessageHouseService extends BaseService {

	@Resource
	MessageDAO messageDAO;
	
	@Resource
	MessageHouseDAO messageHouseDAO;
	
	/**
	 * 管理员发布消息
	 * @param message
	 * @param houseIds
	 * @throws Exception
	 */
	public void addMessage(Message message,String houseIds) throws Exception{
		if(null != message.getId() && !"".equals(message.getId())){
			boundMessage(message, houseIds);
		}else{
			message.setIsAll(Constants.IS_ALL);
			message.setCreateDate(new Date());
			messageDAO.save(message);
			if(null != houseIds && !"".equals(houseIds)){
				message.setIsAll(Constants.NOT_ALL);
				messageDAO.updateObject(message);
				for(String houseId : houseIds.split(",")){
					HrHouses house = new HrHouses(houseId);
					
					MessageHouse messageHouse = new MessageHouse(house, message);
					messageHouseDAO.save(messageHouse);
				}
			}
		}
	}
	
	/**
	 * 消息绑定楼盘
	 * @param favorableId
	 * @param houseIds
	 */
	private void boundMessage(Message message,String houseIds) throws Exception{
		String messageId = message.getId();
		deleteMessageHouseByMessageId(messageId);
		if(null != houseIds && !"".equals(houseIds)){
			message.setIsAll(Constants.NOT_ALL);
			messageDAO.updateObject(message);
			for(String houseId : houseIds.split(",")){
				HrHouses house = new HrHouses(houseId);
				if(getMessageHouseListCount(messageId,houseId)==0){
					MessageHouse favorableHouse = new MessageHouse(house, message);
					messageHouseDAO.save(favorableHouse);
				}
			}
		}else{
			message.setIsAll(Constants.IS_ALL);
			messageDAO.updateObject(message);
		}
	}
	
	public long getMessageHouseListCount(String messageId,String houseId)
			throws Exception{
		return messageHouseDAO.findMessageHouseListCount(messageId, houseId);
	}
	
	public List<MessageHouse> getMessageHouseList(String messageId,String houseId,
			int pageIndex,int pageSize) throws Exception{
		return messageHouseDAO.findMessageHouseList(messageId, houseId, pageIndex, pageSize);
	}
	
	public void deleteMessageHouse(String ids) throws Exception{
		if(ids == null) return ;
		for(String id :ids.split(",")){
			messageHouseDAO.deleteMessageHouse(id);
		}
	}
	private void deleteMessageHouseByMessageId(String messageId) throws Exception{
		messageHouseDAO.deleteMessageHouseByMessageId(messageId);
	}
}
